<template>
  <div class="aab-installer">
    <Toast 
      :show="toast.show" 
      :message="toast.message" 
      :type="toast.type" 
    />
    
    <div class="form-group full-width">
      <input 
        type="file" 
        id="file" 
        ref="fileInput" 
        @change="handleFileUpload" 
        accept=".aab"
      />
    </div>
    
    <div class="device-selection" v-if="devices.length > 0">
      <div class="form-group">
        <label for="device">选择设备：</label>
        <select id="device" v-model="selectedDevice">
          <option value="">请选择设备</option>
          <option 
            v-for="device in devices" 
            :key="device.id" 
            :value="device.id"
          >
            {{ device.id }}
          </option>
        </select>
      </div>
    </div>
    <div v-else class="no-devices">
      未检测到设备，请连接设备后重试
    </div>

    <button 
      @click="installAab" 
      :disabled="!file || !selectedDevice"
    >
      安装到设备
    </button>

    <div v-if="uploading" class="progress">
      <div class="progress-bar" :style="{ width: progress + '%' }"></div>
    </div>
  </div>
</template>

<script>
import Toast from './Toast.vue'

export default {
  components: {
    Toast
  },
  data() {
    return {
      file: null,
      devices: [],
      selectedDevice: '',
      uploading: false,
      progress: 0,
      pollInterval: null,
      toast: {
        show: false,
        message: '',
        type: 'info',
        timer: null
      }
    };
  },
  mounted() {
    this.startDevicePolling();
  },
  beforeDestroy() {
    this.stopDevicePolling();
  },
  methods: {
    startDevicePolling() {
      this.fetchDevices(); // 立即获取一次
      // 每秒轮询一次设备列表
      this.pollInterval = setInterval(() => {
        this.fetchDevices();
      }, 1000);
    },
    stopDevicePolling() {
      if (this.pollInterval) {
        clearInterval(this.pollInterval);
      }
    },
    async fetchDevices() {
      try {
        const response = await fetch(`${process.env.VUE_APP_API_BASE_URL}/api/devices`);
        const data = await response.json();
        this.devices = data.devices;
        
        // 如果没有选择设备且有可用设备，自动选择第一个
        if (!this.selectedDevice && this.devices.length > 0) {
          this.selectedDevice = this.devices[0].id;
        }
      } catch (error) {
        console.error('Error fetching devices:', error);
      }
    },
    handleFileUpload(event) {
      this.file = event.target.files[0];
    },
    showToast(message, type = 'info', duration = 3000) {
      // 清除之前的定时器
      if (this.toast.timer) {
        clearTimeout(this.toast.timer);
      }
      
      // 显示新的提示
      this.toast.show = true;
      this.toast.message = message;
      this.toast.type = type;
      
      // 设置定时器自动关闭
      this.toast.timer = setTimeout(() => {
        this.toast.show = false;
      }, duration);
    },
    installAab() {
      if (!this.file || !this.selectedDevice) return;

      this.uploading = true;
      const formData = new FormData();
      formData.append('file', this.file);
      formData.append('deviceId', this.selectedDevice);

      const xhr = new XMLHttpRequest();
      xhr.open('POST', `${process.env.VUE_APP_API_BASE_URL}/api/install`, true);

      xhr.upload.onprogress = (event) => {
        if (event.lengthComputable) {
          this.progress = Math.round((event.loaded / event.total) * 100);
        }
      };

      xhr.onload = () => {
        if (xhr.status === 200) {
          this.showToast('安装成功！', 'success');
        } else {
          try {
            const response = JSON.parse(xhr.responseText);
            this.showToast(response.error || '安装失败，请重试！', 'error');
          } catch {
            this.showToast('安装失败，请重试！', 'error');
          }
        }
        this.uploading = false;
        this.progress = 0;
        this.resetForm();
      };

      xhr.onerror = () => {
        this.showToast('网络错误，请检查网络连接！', 'error');
        this.uploading = false;
        this.progress = 0;
      };

      xhr.send(formData);
    },
    resetForm() {
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = '';
      }
      this.file = null;
    }
  }
};
</script>

<style scoped>
.aab-installer {
  max-width: 500px;
  margin: 0 auto;
}

.form-group {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.form-group.full-width {
  display: block;
}

.form-group label {
  margin-right: 10px;
  white-space: nowrap;
}

select {
  height: 38px;
  padding: 0 10px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 19px;
  background-color: white;
  color: #555;
  transition: all 0.3s ease;
  flex: 1;
}

input[type="file"] {
  width: 100%;
  height: 38px;
  padding: 0;
  line-height: 34px;
  border: 1px solid #ccc;
  border-radius: 19px;
}

input[type="file"]::-webkit-file-upload-button,
input[type="file"]::file-selector-button {
  height: 38px;
  padding: 0 10px;
  font-size: 14px;
  border: none;
  border-right: 1px solid #ccc;
  background-color: #f8f8f8;
  color: #555;
  transition: all 0.3s ease;
  border-radius: 19px 0 0 19px;
}

button {
  display: block;
  width: 100%;
  max-width: 300px;
  height: 38px;
  margin: 20px auto;
  padding: 0 20px;
  font-size: 16px;
  font-weight: bold;
  color: white;
  background-color: #4CAF50;
  border: none;
  border-radius: 19px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover:not(:disabled) {
  background-color: #45a049;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.progress {
  width: 100%;
  background-color: #f3f3f3;
  border-radius: 8px;
  overflow: hidden;
  margin-top: 20px;
}

.progress-bar {
  background-color: rgba(76, 175, 80, 0.8);
  height: 16px;
  transition: width 0.4s ease;
}

.no-devices {
  text-align: center;
  color: #666;
  margin: 20px 0;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 19px;
}

/* 可以添加一些过渡动画样式 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style> 